package com.hnas.eCard.web;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hnas.account.orm.Account;
import com.hnas.account.service.AccountService;
import com.hnas.api.dto.DTOResult;
import com.hnas.common.interfacedsc.InterfaceDsc;
import com.hnas.common.outdto.GetBalanceReceive;
import com.hnas.common.outdto.GetCardInfoByCardNoForm;
import com.hnas.common.outdto.GetCardInfoByCardNoReceive;
import com.hnas.common.util.CommonReturn;
import com.hnas.common.util.CommonUtils;
import com.hnas.common.util.PostServerInfoGet;
import com.hnas.common.util.ResultCode;
import com.hnas.core.util.DateUtil;
import com.hnas.core.util.StringUtil;
import com.hnas.eCard.domain.CardTrailStatus;
import com.hnas.eCard.domain.ECardCommonFinalValue;
import com.hnas.eCard.domain.SearchECardStatus;
import com.hnas.eCard.orm.AccECard;
import com.hnas.eCard.orm.CardTrail;
import com.hnas.eCard.orm.Merchant;
import com.hnas.eCard.orm.MerchantDetail;
import com.hnas.eCard.service.AccECardService;
import com.hnas.eCard.service.CardTrailService;
import com.hnas.eCard.service.MerchantDetailService;
import com.hnas.eCard.service.MerchantService;
import com.hnas.eastsquare.util.JedisPoolUtil;

import redis.clients.jedis.Jedis;

@Controller
@RequestMapping("/interfaces/eCard")
public class ECardController {

	private static Log log = LogFactory.getLog(ECardController.class);
	
	private static ObjectMapper objectMapper = new ObjectMapper();
	
	@Value("#{component.pic_suffix}")
	private String picSuffix;

	@Autowired
	private AccECardService accECardService;

	@Autowired
	private CardTrailService cardTrailService;
	
	@Autowired
	private AccountService accountService;
	
	@Autowired
	private PostServerInfoGet postServerInfoGet;
	@Autowired
	private JedisPoolUtil jedisPoolUtil;
	@Autowired
	private MerchantService merchantService;
	@Autowired
	private MerchantDetailService merchantDetailService;
	
	/**
	 * 根据账户id和卡状态查询电子卡列表
	 */
	@RequestMapping(value = "/queryCardInfoList")
	// @RequestMapping(value = "/queryCardInfoList", method = RequestMethod.POST)
	@ResponseBody
	public String queryCardInfoList(HttpServletRequest request, HttpServletResponse response) {
		DTOResult dtoResult = new DTOResult();
		JSONObject result = new JSONObject();
		try {
			String sendData = request.getParameter(ECardCommonFinalValue.SEND_DATA);
			if (StringUtil.isEmpty(sendData)) {
				// 请求参数有问题
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_10000, result.toJSONString());
			}
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String accId = jo.getString(ECardCommonFinalValue.acc_id);
			if (StringUtil.isEmpty(accId)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_012, result.toJSONString());
			}
			String ecardStatus = jo.getString(ECardCommonFinalValue.ecard_status);
			if (StringUtil.isEmpty(ecardStatus)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_186, result.toJSONString());
			}
			// 如果查询状态是已收到 手机号码为必填
			String phoneNo = null;
			if (SearchECardStatus.RECEIVED.equals(ecardStatus)) {
				phoneNo = jo.getString(ECardCommonFinalValue.phone_no);
				if (StringUtil.isEmpty(phoneNo)) {
					return CommonUtils.createResult(dtoResult, ResultCode.ERROR_003, result.toJSONString());
				}
			}
			String pageSize = jo.getString(ECardCommonFinalValue.page_size);
			if (StringUtil.isEmpty(pageSize)) {
				pageSize = ECardCommonFinalValue.PAGE_SIZE;
			}
			String pageNo = jo.getString(ECardCommonFinalValue.page_no);
			if (StringUtil.isEmpty(pageNo)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_187, result.toJSONString());
			}
			if (SearchECardStatus.USED.equals(ecardStatus) || SearchECardStatus.BACK.equals(ecardStatus)) {
				result = this.accECardService.findECardsByStatus(accId, ecardStatus, Integer.parseInt(pageNo), Integer.parseInt(pageSize));
			} else if (SearchECardStatus.RECEIVED.equals(ecardStatus) || SearchECardStatus.PRESENTED.equals(ecardStatus)) {
				result = this.cardTrailService.findECardsByStatus(accId, phoneNo, ecardStatus, Integer.parseInt(pageNo), Integer.parseInt(pageSize));
			}
			return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, result.toJSONString());
		} catch (Exception e) {
			log.error("根据账户id和卡状态查询电子卡列表返回结果异常==>" + e.getMessage());
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_188, result.toJSONString());
		}
	}
	
	/**
	 * 赠送电子卡
	 */
	@RequestMapping(value = "/sendECard")
	// @RequestMapping(value = "/sendECard", method = RequestMethod.POST)
	@ResponseBody
	public String sendECard(HttpServletRequest request, HttpServletResponse response) {
		DTOResult dtoResult = new DTOResult();
		JSONObject result = new JSONObject();
		try {
			String sendData = request.getParameter(ECardCommonFinalValue.SEND_DATA);
			if (StringUtil.isEmpty(sendData)) {
				// 请求参数有问题
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_10000, result.toJSONString());
			}
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String accId = jo.getString(ECardCommonFinalValue.acc_id);
			if (StringUtil.isEmpty(accId)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_012, result.toJSONString());
			}
			String cardNo = jo.getString(ECardCommonFinalValue.card_no);
			if (StringUtil.isEmpty(cardNo)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_189, result.toJSONString());
			}
			String receivePhoneNo = jo.getString(ECardCommonFinalValue.receive_phone_no);
			if (StringUtil.isEmpty(receivePhoneNo)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_190, result.toJSONString());
			}
			String sendPhoneNo = jo.getString(ECardCommonFinalValue.send_phone_no);
			if (StringUtil.isEmpty(sendPhoneNo)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_191, result.toJSONString());
			}
			Account account = this.accountService.findById(accId);
			if(account == null) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_217, result.toJSONString());
			}
			if(receivePhoneNo.equals(account.getPhoneNo())) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_220, result.toJSONString());
			}
			this.accECardService.sendECard(dtoResult, jo);
			return CommonUtils.createResult(dtoResult, dtoResult.getResultData());
		} catch (Exception e) {
			log.error("赠送电子卡返回结果异常111111=>" + e.getMessage());
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_192, result.toJSONString());
		}
	}
	
	/**
	 * 领取分享的电子卡
	 */
	@RequestMapping(value = "/shareReceiveECard")
	// @RequestMapping(value = "/receiveOrRefuseECard", method = RequestMethod.POST)
	@ResponseBody
	public String shareReceiveECard(HttpServletRequest request, HttpServletResponse response) {
		DTOResult dtoResult = new DTOResult();
		JSONObject result = new JSONObject();
		Jedis jedis = jedisPoolUtil.getJedis();
		try {
			String sendData = request.getParameter(ECardCommonFinalValue.SEND_DATA);
			if (StringUtil.isEmpty(sendData)) {
				// 请求参数有问题
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_10000, result.toJSONString());
			}
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String accId = jo.getString(ECardCommonFinalValue.acc_id);
			if (StringUtil.isEmpty(accId)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_012, result.toJSONString());
			}
			String shareCode = jo.getString(ECardCommonFinalValue.share_code);
			if (StringUtil.isEmpty(shareCode)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_189, result.toJSONString());
			}
			Long incrBy = jedis.incrBy(shareCode,1l);
			if(incrBy > 1) {
				jedis.decrBy(shareCode, 1);
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_229,null);
			}else {
				try {
					this.accECardService.shareReceiveECard(dtoResult, jo);
					if(!ResultCode.SUCCESS.equals(dtoResult.getResultCode())) {
						jedis.decrBy(shareCode, 1);
					}
					return CommonUtils.createResult(dtoResult, dtoResult.getResultData());
				}catch(Exception e) {
					log.error("领取分享电子卡失败", e);
					jedis.decrBy(shareCode, 1);
					return CommonUtils.createResult(dtoResult, ResultCode.ERROR_228,null);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("领取或拒绝电子卡返回结果异常==>" + e.getMessage());
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_197, result.toJSONString());
		} finally {
			if(jedis != null) jedis.close();
		}
	}
	
	/**
	 * 领取或拒绝电子卡
	 */
	@RequestMapping(value = "/receiveOrRefuseECard")
	// @RequestMapping(value = "/receiveOrRefuseECard", method = RequestMethod.POST)
	@ResponseBody
	public String receiveOrRefuseECard(HttpServletRequest request, HttpServletResponse response) {
		DTOResult dtoResult = new DTOResult();
		JSONObject result = new JSONObject();
		try {
			String sendData = request.getParameter(ECardCommonFinalValue.SEND_DATA);
			if (StringUtil.isEmpty(sendData)) {
				// 请求参数有问题
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_10000, result.toJSONString());
			}
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String accId = jo.getString(ECardCommonFinalValue.acc_id);
			if (StringUtil.isEmpty(accId)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_012, result.toJSONString());
			}
			String cardNo = jo.getString(ECardCommonFinalValue.card_no);
			if (StringUtil.isEmpty(cardNo)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_189, result.toJSONString());
			}
			String receiveType = jo.getString(ECardCommonFinalValue.receive_type);
			if (StringUtil.isEmpty(receiveType)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_195, result.toJSONString());
			}
			if(!ECardCommonFinalValue.RECEIVE_TYPE.equals(receiveType) && !ECardCommonFinalValue.REFUSE_TYPE.equals(receiveType)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_196, result.toJSONString());
			}
			this.accECardService.receiveOrRefuseECard(dtoResult, jo);
			
			return CommonUtils.createResult(dtoResult, dtoResult.getResultData());
		} catch (Exception e) {
			log.error("领取或拒绝电子卡返回结果异常==>" + e.getMessage());
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_197, result.toJSONString());
		}
	}
	
	/**
	 * 电子卡退卡申请
	 */
	@RequestMapping(value = "/backCardApply")
	// @RequestMapping(value = "/backCardApply", method = RequestMethod.POST)
	@ResponseBody
	public String backCardApply(HttpServletRequest request, HttpServletResponse response) {
		DTOResult dtoResult = new DTOResult();
		JSONObject result = new JSONObject();
		try {
			String sendData = request.getParameter(ECardCommonFinalValue.SEND_DATA);
			if (StringUtil.isEmpty(sendData)) {
				// 请求参数有问题
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_10000, result.toJSONString());
			}
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String accId = jo.getString(ECardCommonFinalValue.acc_id);
			if (StringUtil.isEmpty(accId)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_012, result.toJSONString());
			}
			String cardNo = jo.getString(ECardCommonFinalValue.card_no);
			if (StringUtil.isEmpty(cardNo)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_189, result.toJSONString());
			}
			this.accECardService.backCardApply(dtoResult, jo);
			return CommonUtils.createResult(dtoResult, dtoResult.getResultData());
		} catch (Exception e) {
			log.error("电子卡退卡申请返回结果异常==>" + e.getMessage());
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_202, result.toJSONString());
		}
	}
	
	/**
	 * 电子卡卡号秘钥校验
	 */
	@RequestMapping(value = "/checkCardSecretKey")
	// @RequestMapping(value = "/checkCardSecretKey", method = RequestMethod.POST)
	@ResponseBody
	public String checkCardSecretKey(HttpServletRequest request, HttpServletResponse response) {
		DTOResult dtoResult = new DTOResult();
		JSONObject result = new JSONObject();
		try {
			String sendData = request.getParameter(ECardCommonFinalValue.SEND_DATA);
			if (StringUtil.isEmpty(sendData)) {
				// 请求参数有问题
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_10000, result.toJSONString());
			}
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String accId = jo.getString(ECardCommonFinalValue.acc_id);
			if (StringUtil.isEmpty(accId)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_012, result.toJSONString());
			}
			String cardNo = jo.getString(ECardCommonFinalValue.card_no);
			if (StringUtil.isEmpty(cardNo)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_189, result.toJSONString());
			}
			String secretKey = jo.getString(ECardCommonFinalValue.secret_key);
			if (StringUtil.isEmpty(secretKey)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_203, result.toJSONString());
			}
			GetCardInfoByCardNoForm form = new GetCardInfoByCardNoForm();
			form.setCardNo(cardNo);
			CommonReturn ret = this.postServerInfoGet.GetCardInfoByCardNo(form);
			if(ResultCode.SUCCESS.equals(ret.getResultCode())){
				GetCardInfoByCardNoReceive receive = (GetCardInfoByCardNoReceive) ret.getResultData();
				String cardStat = receive.getCARD_STAT();
				if(!"03".equals(cardStat)) {
					return CommonUtils.createResult(dtoResult, ResultCode.ERROR_233, result.toJSONString());
				}
			}else {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_232, result.toJSONString());
			}
			
			this.accECardService.checkCardSecretKey(dtoResult, jo);
			return CommonUtils.createResult(dtoResult, dtoResult.getResultData());
		} catch (Exception e) {
			log.error("电子卡卡号秘钥校验返回结果异常==>" + e.getMessage());
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_204, result.toJSONString());
		}
	}
	
	/**
	 * 领取或拒绝电子卡
	 */
	@RequestMapping(value = "/cancelGiveECard", method = RequestMethod.POST)
	@ResponseBody
	public String cancelGiveECard(HttpServletRequest request, HttpServletResponse response) {
		DTOResult dtoResult = new DTOResult();
		JSONObject result = new JSONObject();
		try {
			String sendData = request.getParameter(ECardCommonFinalValue.SEND_DATA);
			if (StringUtil.isEmpty(sendData)) {
				// 请求参数有问题
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_10000, result.toJSONString());
			}
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String accId = jo.getString(ECardCommonFinalValue.acc_id);
			if (StringUtil.isEmpty(accId)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_012, result.toJSONString());
			}
			String cardNo = jo.getString(ECardCommonFinalValue.card_no);
			if (StringUtil.isEmpty(cardNo)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_189, result.toJSONString());
			}
			this.accECardService.cancelGiveECard(dtoResult, jo);
			return CommonUtils.createResult(dtoResult, dtoResult.getResultData());
		} catch (Exception e) {
			log.error("取消赠送电子卡返回结果异常==>" + e.getMessage());
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_216, result.toJSONString());
		}
	}
	
	/**
	 * 通过卡号和账户id获取卡余额
	 * @param request
	 * @return
	 * @throws JsonProcessingException
	 */
	@RequestMapping(value = "/getCardBalanceByCardNo", method = RequestMethod.POST)
	@ResponseBody
	public String getCardBalanceByCardNo(HttpServletRequest request) {
		DTOResult dtoResult = new DTOResult();
		String sendData = "";
		try {
			sendData = request.getParameter("sendData");
			// 入参为空判断
			if (StringUtil.isEmpty(sendData)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_10000, null);
			}
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String accId = jo.getString("acc_id");
			String cardNo = jo.getString("card_no");
			String subCode = jo.getString("sub_code");
			
			if (StringUtil.isEmpty(accId)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_012, null);
			}
			
			if (StringUtil.isEmpty(cardNo)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_045, null);
			}
			
			if (StringUtil.isEmpty(subCode)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_094, null);
			}
			//查余额
			CommonReturn getBala = postServerInfoGet.getBalanceInfo(cardNo, subCode);
			if (null != getBala) {
				if (ResultCode.SUCCESS.equals(getBala.getResultCode())) {
					GetBalanceReceive currBala = (GetBalanceReceive) getBala.getResultData();
					return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, objectMapper.writeValueAsString(currBala));
				}
			}
			// 查询结果为空
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_181, null);
		} catch (Exception e) {
			// 日志记录
			log.error(DateUtil.dateTimeToString(new Date()) + "调用接口：" + InterfaceDsc.APP_WXXNK_GetBalance
					+ ",请求数据:入参为:" + sendData + "  出错:" , e);
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_105, null);
		} finally {
			// 日志记录
			log.info(DateUtil.dateTimeToString(new Date()) + "调用接口：" + InterfaceDsc.APP_WXXNK_GetBalance
					+ ",请求数据:入参为:" + sendData + "  返回参数:" + dtoResult);
		}
	}
	
	/**
	 * 生成电子卡分享码
	 */
	@RequestMapping(value = "/createShareCode")
	@ResponseBody
	public String createShareCode(HttpServletRequest request, HttpServletResponse response) {
		DTOResult dtoResult = new DTOResult();
		JSONObject result = new JSONObject();
		Jedis jedis = jedisPoolUtil.getJedis();
		try {
			String sendData = request.getParameter(ECardCommonFinalValue.SEND_DATA);
			if (StringUtil.isEmpty(sendData)) {
				// 请求参数有问题
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_10000, result.toJSONString());
			}
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String sendAccId = jo.getString(ECardCommonFinalValue.send_acc_id);
			if (StringUtil.isEmpty(sendAccId)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_012, result.toJSONString());
			}
			String cardNo = jo.getString(ECardCommonFinalValue.card_no);
			if (StringUtil.isEmpty(cardNo)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_189, result.toJSONString());
			}
			String sendMsg= jo.getString(ECardCommonFinalValue.send_msg);
			String sendName = jo.getString(ECardCommonFinalValue.send_name);
			String sendWxName = jo.getString(ECardCommonFinalValue.send_wx_name);
			String sendWxImage = jo.getString(ECardCommonFinalValue.send_wx_image);
			String shareCode = jo.getString(ECardCommonFinalValue.share_code);
			Account account = this.accountService.findById(sendAccId);
			AccECard searchVO = new AccECard();
			searchVO.setCardNo(cardNo);
			searchVO.setAccId(sendAccId);
			List<AccECard> list = this.accECardService.findByECard(searchVO);
			if(list == null || list.size() <= 0) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_224, result.toJSONString());
			}
			JSONObject ret = new JSONObject();
			Long shareCodeVal = jedis.incrBy("share_"+shareCode, 1);
			if(shareCodeVal > 1) {
				ret.put(ECardCommonFinalValue.opt_status, ECardCommonFinalValue.OPT_SUCCESS);
			}else {
				AccECard accECard = list.get(0);
				CardTrail cardTrailOld = this.cardTrailService.findByShareCode(shareCode);
				if(cardTrailOld != null) {
					ret.put(ECardCommonFinalValue.opt_status, ECardCommonFinalValue.OPT_SUCCESS);
				}else {
					CardTrail cardTrail = new CardTrail();
					cardTrail.setId(CommonUtils.getUUID());
					cardTrail.setSendAccId(sendAccId);
					cardTrail.setSendPhoneNo(account.getPhoneNo());
					cardTrail.setSendName(sendName);
					cardTrail.setSendCardNo(cardNo);
					//获取当前余额
					CommonReturn getBala = postServerInfoGet.getBalanceInfo(cardNo, "224102");
					if (null != getBala) {
						if (ResultCode.SUCCESS.equals(getBala.getResultCode())) {
							GetBalanceReceive currBala = (GetBalanceReceive) getBala.getResultData();
							cardTrail.setCurrentBalance(currBala.getBALANCE());
						}
					}
					cardTrail.setSendMsg(sendMsg);
					cardTrail.setReceivePhoneNo(null);
					cardTrail.setReceiveName(null);
					cardTrail.setStatus(CardTrailStatus.RECEIVING_GIVING);
					cardTrail.setSort(ECardCommonFinalValue.SORT_HEAD);
					cardTrail.setSendWxImage(sendWxImage);
					cardTrail.setSendWxName(sendWxName);
					cardTrail.setCreateType(Integer.valueOf(ECardCommonFinalValue.SHARE_FOR_OTHER));
					cardTrail.setShareCode(shareCode);
					boolean res = this.cardTrailService.shareECard(accECard, cardTrail);
					if(res) {
						ret.put(ECardCommonFinalValue.opt_status, ECardCommonFinalValue.OPT_SUCCESS);
					}else {
						ret.put(ECardCommonFinalValue.share_code, ECardCommonFinalValue.OPT_FAIL);
					}
				}
			}
			return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, objectMapper.writeValueAsString(ret));
		} catch (Exception e) {
			e.printStackTrace();
			log.error("生成分享码结果异常==>" + e.getMessage());
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_197, result.toJSONString());
		} finally {
			if(jedis != null) jedis.close();
		}
	}
	
	/**
	 * 根据分享码获取电子卡信息
	 */
	@RequestMapping(value = "/getCardInfoByShareCode")
	@ResponseBody
	public String getCardInfoByShareCode(HttpServletRequest request, HttpServletResponse response) {
		DTOResult dtoResult = new DTOResult();
		JSONObject result = new JSONObject();
		try {
			String sendData = request.getParameter(ECardCommonFinalValue.SEND_DATA);
			if (StringUtil.isEmpty(sendData)) {
				// 请求参数有问题
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_10000, result.toJSONString());
			}
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String shareCode = jo.getString(ECardCommonFinalValue.share_code);
			if(StringUtil.isEmpty(shareCode)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_225, null);
			}
			//判断卡是否被领过了(从卡轨迹中找第一条记录按时间顺序排)
			dtoResult = this.cardTrailService.findCardInfo(shareCode,dtoResult);
			return CommonUtils.createResult(dtoResult, dtoResult.getResultCode(), dtoResult.getResultData());
		} catch (Exception e) {
			e.printStackTrace();
			log.error("领取或拒绝电子卡返回结果异常==>" + e.getMessage());
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_197, result.toJSONString());
		}
	}
	
	/**
	 * 解绑电子卡
	 */
	@RequestMapping(value = "/unbindECard")
	@ResponseBody
	public String unbindECard(HttpServletRequest request, HttpServletResponse response) {
		DTOResult dtoResult = new DTOResult();
		JSONObject result = new JSONObject();
		try {
			String sendData = request.getParameter(ECardCommonFinalValue.SEND_DATA);
			if (StringUtil.isEmpty(sendData)) {
				// 请求参数有问题
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_10000, result.toJSONString());
			}
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String accId = jo.getString(ECardCommonFinalValue.acc_id);
			String cardNo = jo.getString(ECardCommonFinalValue.card_no);
			if(StringUtil.isEmpty(accId)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_012, null);
			}
			if(StringUtil.isEmpty(cardNo)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_189, null);
			}
			int res = this.accECardService.unbindECard(accId,cardNo);
			if(res > 0) {
				result.put(ECardCommonFinalValue.opt_status, "1");
			}else {
				result.put(ECardCommonFinalValue.opt_status, "0");
			}
			return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, result.toJSONString());
		} catch (Exception e) {
			e.printStackTrace();
			log.error("解绑电子卡结果异常==>",e);
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_197, result.toJSONString());
		}
	}
	
	/**
	 * 查询商户信息
	 */
	@RequestMapping(value = "/getAllMerchant")
	@ResponseBody
	public String getAllMerchant(HttpServletRequest request, HttpServletResponse response) {
		DTOResult dtoResult = new DTOResult();
		JSONObject result = new JSONObject();
		try {
			String sendData = request.getParameter(ECardCommonFinalValue.SEND_DATA);
			if (StringUtil.isEmpty(sendData)) {
				// 请求参数有问题
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_10000, result.toJSONString());
			}
			List<Merchant> list = this.merchantService.listAll();
			JSONArray ja = new JSONArray();
			if(list != null && list.size() > 0) {
				for(Merchant m : list) {
					JSONObject jo = new JSONObject();
					jo.put(ECardCommonFinalValue.merchant_id, m.getId());
					jo.put(ECardCommonFinalValue.merchant_name, m.getName());
					jo.put(ECardCommonFinalValue.merchant_pic, picSuffix+m.getPic());
					ja.add(jo);
				}
			}
			result.put("merchant_list", ja);
			return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, result.toJSONString());
		} catch (Exception e) {
			e.printStackTrace();
			log.error("解绑电子卡结果异常==>",e);
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_197, result.toJSONString());
		}
	}
	
	/**
	 * 查询商户详情信息
	 */
	@RequestMapping(value = "/getMerchantDetail")
	@ResponseBody
	public String getMerchantDetail(HttpServletRequest request, HttpServletResponse response) {
		DTOResult dtoResult = new DTOResult();
		JSONObject result = new JSONObject();
		try {
			String sendData = request.getParameter(ECardCommonFinalValue.SEND_DATA);
			if (StringUtil.isEmpty(sendData)) {
				// 请求参数有问题
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_10000, result.toJSONString());
			}
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String merchantId = jo.getString(ECardCommonFinalValue.merchant_id);
			if(StringUtil.isEmpty(merchantId)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_230, null);
			}
			Merchant merchant = this.merchantService.findById(merchantId);
			List<MerchantDetail> list = this.merchantDetailService.listAllByMerchantId(merchantId);
			JSONArray ja = new JSONArray();
			if(list != null && list.size() > 0) {
				for(MerchantDetail m : list) {
					JSONObject temp = new JSONObject();
					temp.put(ECardCommonFinalValue.detail_id, m.getId());
					temp.put(ECardCommonFinalValue.detail_name, m.getName());
					temp.put(ECardCommonFinalValue.detail_address, m.getAddress());
					temp.put(ECardCommonFinalValue.detail_remark, m.getRemark());
					temp.put(ECardCommonFinalValue.detail_pic, merchant==null?"":picSuffix+merchant.getPic());
					ja.add(temp);
				}
			}
			result.put("detail_list", ja);
			return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, result.toJSONString());
		} catch (Exception e) {
			e.printStackTrace();
			log.error("解绑电子卡结果异常==>",e);
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_197, result.toJSONString());
		}
	}
	
	/**
	 * 通过卡号和账户id查询实体卡余额
	 * @param request
	 * @return
	 * @throws JsonProcessingException
	 */
	@RequestMapping(value = "/checkBindEntityCard", method = RequestMethod.POST)
	@ResponseBody
	public String checkBindEntityCard(HttpServletRequest request) {
		DTOResult dtoResult = new DTOResult();
		String sendData = "";
		try {
			sendData = request.getParameter("sendData");
			// 入参为空判断
			if (StringUtil.isEmpty(sendData)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_10000, null);
			}
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String cardNo = jo.getString("card_no");
			
			if (StringUtil.isEmpty(cardNo)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_045, null);
			}
			
			//先查询该卡是否被绑定过
			AccECard criteria = new AccECard();
			criteria.setCardNo(cardNo);
			List<AccECard> findByECard = this.accECardService.findByECard(criteria);
			JSONObject res = new JSONObject();
			if(findByECard != null && findByECard.size() > 0) {
				res.put("bind_flag", "1");
			}else {
				res.put("bind_flag", "0");
			}
			// 查询结果为空
			return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, objectMapper.writeValueAsString(res));
		} catch (Exception e) {
			// 日志记录
			log.error(DateUtil.dateTimeToString(new Date()) + "调用接口：" + InterfaceDsc.APP_WXXNK_GetBalance
					+ ",请求数据:入参为:" + sendData + "  出错:" , e);
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_105, null);
		} finally {
			// 日志记录
			log.info(DateUtil.dateTimeToString(new Date()) + "调用接口：" + InterfaceDsc.APP_WXXNK_GetBalance
					+ ",请求数据:入参为:" + sendData + "  返回参数:" + dtoResult);
		}
	}
}
